package mylibrary.security;

import java.security.MessageDigest;
import java.security.SecureRandom;

import org.apache.commons.codec.binary.Hex;

public class SHA1 {

	public static void main(String[] args) throws Exception {
	
		
		//System.out.println(createEncryptedKey());
		
		System.out.println(SHA1("password1"));
		
	}
	
	public static String SHA1(String s) throws Exception {
		MessageDigest messageDigest = MessageDigest.getInstance("SHA-224");
		//messageDigest.reset();
		messageDigest.update(s.getBytes("UTF-8"));
		
		byte[] resultByte = messageDigest.digest();
		String result = new String(Hex.encodeHex(resultByte));
		
		return result;
	}
	
	public static String createEncryptedKey() throws Exception {
		
		
		//伪随机数生成器     Pseudo-random number generator

		SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
		
		MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
		
		//在调用方从 getInstance 调用中获得 SecureRandom 对象之后，它可以调用 nextBytes() 来生成随机字节：
		byte[] randomBytes = new byte[20];
		random.nextBytes(randomBytes);
		
		byte[] hash = messageDigest.digest(randomBytes);
		
		return new String(Hex.encodeHex(hash));
		
//		StringBuffer result = new StringBuffer(hash.length * 2);
//		for (Byte temp : hash) {
//			result.append(String.format("%02X", temp));
//		}
//		return result.toString();
		
	}
	

}
